﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Domain.Model.Abstract;

using NHibernate.Validator.Constraints;

namespace Domain.Model
{
    public class Form : Entity
    {
        public static string PROJECT_FORM = "Project Form";
        public static string SUBPROJECT_FORM = "Subproject Form";

        #region Properties

        [NotNull]
        public virtual string Name { get; set; }

        public virtual IList<FormElement> FormElements { get; set; }

        #endregion

        #region Fields

        #endregion

        #region Constructor

        public Form(string name)
        {
            Name = name;

            FormElements = new List<FormElement>();
        }

        public Form()
            : this("unknownWebform")
        { 
        
        }

        #endregion

        #region Public interface

        public virtual void AddFormElement(FormElement element)
        {
            element.Form = this;
            FormElements.Add(element);
        }

        public virtual void RemoveFormElement(FormElement element)
        {
            element.Form = null;
            FormElements.Remove(element);

            UpdateElementPositions();
        }

        public virtual FormElement GetElementByName(string name)
        {
            FormElement match = null;

            foreach (var element in FormElements)
            {
                if (element.Name == name)
                    match = element;
            }

            return match;
        }

        #endregion

        #region Private functions

        private void UpdateElementPositions()
        {
            FormElements.OrderBy(x => x.Position);

            int position = 0;

            foreach (var element in FormElements)
            {
                element.Position = position;
                position++;
            }
        }

        #endregion
    }
}